/**
 * 
 */
package edu.buffalo.cse.cse486_586.simpledynamo.provider;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import android.util.Log;

/**
 * @author sravan
 *
 */
public class Utility {
	
	// 0-100
	public static boolean isHashBetweenHashes(String current, String next, String find){
		if(hashCompare(next, current) == 0 || hashCompare(next, find) == 0 
				|| hashCompare(find, current) == 0){
			return false;
		}
		else if(hashCompare(next, current) > 0){
			if(hashCompare(find, current) > 0 && hashCompare(next, find) > 0){
				return true;
			}
			else{
				return false;
			}
		}
		else{ // 90,10
			if(hashCompare(find, current) > 0){ // 91
				return true;
			}
			else if(hashCompare(next, find) > 0){ // 9
				return true;
			}
			else{ // other
				return false;
			}
		}
	}

	public static int hashCompare(String current, String other){
		int curLength = current.length();
		int otherLen = other.length();
		int retValue = 0;
		while(otherLen > 0 && curLength > 0){
			if( current.charAt(curLength-1) == other.charAt(otherLen-1))
				retValue = retValue + (current.charAt(curLength-1) - other.charAt(otherLen-1));
			else
				retValue = (current.charAt(curLength-1) - other.charAt(otherLen-1));

			otherLen--;
			curLength--;
		}
		if(curLength == 0 && otherLen == 0){
			return retValue;
		}
		else if(curLength > 0){
			return 1;
		}
		else if(otherLen > 0){
			return -1;
		}
		Log.d("S_DYNAMO","HASH:"+ " This must not be printed");
		return 0;
	}
	
	public static int resolvePortNumber(String node_id){
		return Integer.parseInt(node_id)*2;
	}
	
	public static String genHash(String input){
		MessageDigest sha1;
		try {
			sha1 = MessageDigest.getInstance("SHA-1");
			byte[] sha1Hash = sha1.digest(input.getBytes());
			Formatter formatter = new Formatter();
			for (byte b : sha1Hash) {
				formatter.format("%02x", b);
			}
			return formatter.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			return null;
		}		
	}
}
